<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="产品名称">
                <a-input v-model="queryParam.search_key" placeholder="请输入产品名称"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="创建时间">
                <a-range-picker
                  format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  @change="onChange"
                  @calendarChange="calendarChange"
                  :ranges="ranges"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button @click="$refs.table.refresh(true)" type="primary">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.search_is_show" @change="onOptionChange">
          <a-radio-button :value="-1"> 全部 </a-radio-button>
          <a-radio-button :value="1"> 使用中 </a-radio-button>
          <a-radio-button :value="0"> 未使用 </a-radio-button>
        </a-radio-group>
        <div>
          <a-button type="primary" @click="onAdd" icon="plus">新增</a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="allChangeStatus('open')">批量启用</a-menu-item>
              <a-menu-item @click="allChangeStatus('disabled')">批量禁用</a-menu-item>
              <a-menu-item @click="allChangeStatus('delete')">批量删除</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>
      <a-alert :message="`已选择 ${selectedRowKeys.length} 项`" v-if="selectedRowKeys.length" style="margin-bottom:16px;" type="info" show-icon />

      <s-table
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        rowKey="id"
        size="default"
        :columns="columns"
        :data="loadData"
        ref="table"
      >
        <a-popconfirm
          placement="topLeft"
          slot="is_show"
          slot-scope="text, record"
          ok-text="确定"
          cancel-text="取消"
          @confirm="changeShow(record)"
        >
          <template slot="title">
            <p>{{ text == 0 ? '是否确定启用' : '是否确定禁用' }}</p>
          </template>
          <a-switch checked-children="开" un-checked-children="关" :checked="text == 1" />
        </a-popconfirm>
        <span slot="created_at" slot-scope="text">{{ text | timeFormat }}</span>
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除该产品吗？" @confirm="handleDelete(record)">
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm>
        </span>
      </s-table>

      <a-modal
        :title="isNew ? '新增产品' : '编辑产品'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        v-model="visible"
        @ok="handleOk"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" style="display: none" label="主键" hasFeedback>
            <a-input placeholder="主键" :disabled="!isNew" v-decorator="['id']" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品名称" hasFeedback>
            <a-input
              placeholder="产品名称"
              v-decorator="['product_name', { rules: [{ required: true, message: '请填写产品名称' }] }]"
            />
          </a-form-item>

          <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序" hasFeedback>
            <a-input
              placeholder="排序"
              v-decorator="['sort', { rules: [{ required: true, message: '请填写排序' }], initialValue: 0 }]"
            />
          </a-form-item> -->

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否使用" extra="">
            <a-radio-group v-decorator="['is_show']">
              {{ is_show }}
              <a-radio :value="0"> 禁用 </a-radio>
              <a-radio :value="1"> 启用 </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import pick from 'lodash.pick'
import { STable } from '@/components'
import {
  productEdit,
  getProductList,
  delProduct,
  productShow,
  productBatch,
} from '@/api/plugin/product_traceability/product'
import NoBorderRadio from '@/components/NoBorderRadio/NoBorderRadio'

const STATUS = {
  0: '禁用',
  1: '启用',
}

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '产品名称',
    dataIndex: 'product_name',
  },
  // {
  //   title: '排序',
  //   dataIndex: 'sort',
  //   sorter: (a, b) => a.sort - b.sort
  // },
  {
    title: '状态',
    dataIndex: 'is_show',
    scopedSlots: { customRender: 'is_show' },
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    scopedSlots: {
      customRender: 'created_at',
    },
  },
  {
    title: '操作',
    width: '150px',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'ProductList',
  components: {
    STable,
    NoBorderRadio,
  },
  data() {
    return {
      selectedRowKeys: [],
      isNew: false,
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      form: this.$form.createForm(this),
      // 表头
      columns,
      // 权限树
      permissionTree: [],
      modalLoading: false,
      defaultCheckedKeys: [],
      statusSelectValue: 1,
      // 查询条件参数
      queryParam: {
        search_key: null,
        start_time: null,
        end_time: null,
        search_is_show: -1,
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        return getProductList(parameter).then((res) => {
          console.log('getProductList', res)
          return res.data
        })
      },
    }
  },
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
  },
  created() {},
  activated() {
    this.$refs.table.refresh()
  },
  methods: {
    calendarChange(date, dateString) {
      this.selectDate = date[0]
    },
    onChange(date, dateString) {
      this.queryParam.dateStart = dateString[0]
      this.queryParam.dateEnd = dateString[1]
    },
    changeTab(val) {
      if (val == 1) {
        this.$router.push({ name: 'ProductList' })
      }
      if (val == 2) {
        this.$router.push({ name: 'ProductBatchList' })
      }
      if (val == 3) {
        this.$router.push({ name: 'ProductBatchProcessLogList' })
      }
    },
    onOptionChange() {
      this.$refs.table.refresh()
    },
    changeShow(item) {
      console.log(item)
      const hide = this.$message.loading('请求中...', 0)
      productShow({
        id: item.id,
        is_show: item.is_show,
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('操作成功！')
            this.$refs.table.refresh()
          } else {
            // this.$error({
            //   content: res.msg
            // })
            this.modalLoading = false
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.modalLoading = false
        })
    },
    handleEdit(record) {
      this.isNew = false
      this.visible = true

      record.is_show = parseInt(record.is_show)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['is_show', 'product_name', 'id']))
      })
    },
    resetQueryParams() {
      Object.assign(this.queryParam, {
        search_key: null,
        search_is_show: null,
        dateStart: null,
        dateEnd: null,
      })
      this.$refs.table.refresh(true)
    },
    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return false
        }

        this.modalLoading = true

        productEdit(values)
          .then((res) => {
            console.log(res)
            this.modalLoading = false
            if (res.code !== 0) {
              this.$error({
                content: res.msg,
              })
            } else {
              this.$message.success(res.msg)
              this.visible = false
              this.$refs.table.refresh()
            }
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.modalLoading = false
          })
      })
    },
    onAdd: function () {
      this.isNew = true
      this.visible = true
      this.defaultCheckedKeys = []
    },
    handleDelete: function (record) {
      const hide = this.$message.loading('删除中...', 0)
      delProduct({
        id: record.id,
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success(res.msg)
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
          hide()
        })
    },
    onSelectChange(val) {
      this.selectedRowKeys = val
    },

    // 批量操作员工
    allChangeStatus(e) {
      let that = this
      let text = e == 'open' ? '启用' : e == 'disabled' ? '禁用' : e == 'delete' ? '删除' : ''
      if (this.selectedRowKeys.length) {
        let type = e
        let status = e == 'open' ? 1 : e == 'disabled' ? 0 : e == 'delete' ? 1 : ''
        let param = {
          id: that.selectedRowKeys,
          type,
          status,
        }
        this.$confirm({
          title: '是否批量' + text,
          onOk() {
            that.change(param)
          },
          onCancel() {},
        })
      }
    },

    async change(param) {
      let that = this
      const res = await productBatch(param)
      if (res.code == 0) {
        this.$message.success(res.msg)
        this.$refs.table.refresh()
      }
    },
  },
}
</script>

<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
</style>
